<template>
  <div class="highway-query-container">
    <div class="query-panel">
      <el-card class="query-card">
        <template #header>
          <div class="card-header">
            <h3>高速公路查询</h3>
            <el-button
              v-if="hasEntrances || hasServices"
              type="primary"
              @click="toggleFacilityData"
            >
              <el-icon><PieChart /></el-icon>
              {{ showFacilityData ? '隐藏数据' : '显示数据' }}
            </el-button>
          </div>
        </template>

        <el-tabs v-model="activeTab" @tab-change="handleTabChange" :key="refreshKey">
          <el-tab-pane label="高速公路查询" name="highway">
            <el-input
              v-model="highwayQuery"
              placeholder="请输入高速公路名称或编号"
              clearable
              @keyup.enter="searchHighway"
            >
              <template #append>
                <el-button @click="searchHighway">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>

            <div class="result-list" v-if="highwayResults.length > 0">
              <el-table :data="highwayResults" stripe style="width: 100%">
                <el-table-column prop="highway_name" label="高速公路名称" />
                <el-table-column prop="highway_code" label="编号" width="100" />
                <el-table-column prop="highway_level" label="等级" width="100" />
                <el-table-column prop="status" label="路况" width="100" />
                <el-table-column label="操作" width="120">
                  <template #default="scope">
                    <el-button type="primary" size="small" @click="zoomToHighway(scope.row)">
                      查看
                    </el-button>
                    <el-button type="success" size="small" @click="queryFacilities(scope.row)">
                      设施
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-empty
              v-else-if="hasSearched && highwayResults.length === 0"
              description="未找到匹配的高速公路"
            />
          </el-tab-pane>

          <el-tab-pane label="进出口查询" name="entrance">
            <el-input
              v-model="entranceQuery"
              placeholder="请输入进出口名称或高速公路编号"
              clearable
              @keyup.enter="searchEntrance"
            >
              <template #append>
                <el-button @click="searchEntrance">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>

            <div class="result-list" v-if="entranceResults.length > 0">
              <el-table :data="entranceResults" stripe style="width: 100%">
                <el-table-column prop="entrance_name" label="进出口名称" />
                <el-table-column prop="entrance_type" label="类型" width="100" />
                <el-table-column prop="highway_code" label="所属高速" width="100" />
                <el-table-column label="操作" width="100">
                  <template #default="scope">
                    <el-button type="primary" size="small" @click="zoomToFeature(scope.row,'entrance')">
                      查看
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-empty
              v-else-if="hasSearched && entranceResults.length === 0"
              description="未找到匹配的进出口"
            />
          </el-tab-pane>

          <el-tab-pane label="服务区查询" name="service">
            <el-input
              v-model="serviceQuery"
              placeholder="请输入服务区名称或高速公路编号"
              clearable
              @keyup.enter="searchService"
            >
              <template #append>
                <el-button @click="searchService">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>

            <div class="result-list" v-if="serviceResults.length > 0">
              <el-table :data="serviceResults" stripe style="width: 100%">
                <el-table-column prop="service_name" label="服务区名称" />
                <el-table-column prop="service_level" label="等级" width="100" />
                <el-table-column prop="highway_code" label="所属高速" width="100" />
                <el-table-column label="操作" width="100">
                  <template #default="scope">
                    <el-button type="primary" size="small" @click="zoomToFeature(scope.row,'service')">
                      查看
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-empty
              v-else-if="hasSearched && serviceResults.length === 0"
              description="未找到匹配的服务区"
            />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 设施数据容器 -->
    <div v-if="showFacilityData" class="facility-data-panel" :key="refreshKey">
      <el-card class="data-card">
        <template #header>
          <div class="card-header">
            <h3>{{ currentHighwayName || '高速公路' }}设施数据</h3>
            <el-button type="default" size="small" @click="toggleFacilityData">关闭</el-button>
          </div>
        </template>
        <el-tabs type="border-card">
          <el-tab-pane label="进出口数据">
            <div v-if="entranceResults.length > 0" class="data-container">
              <el-table :data="entranceResults" stripe style="width: 100%">
                <el-table-column prop="entrance_name" label="进出口名称" />
                <el-table-column prop="entrance_type" label="类型" width="100" />
                <el-table-column prop="status" label="状态" width="100" />
                <el-table-column prop="location_desc" label="位置描述" />
              </el-table>
            </div>
            <el-empty v-else description="没有进出口数据"></el-empty>
          </el-tab-pane>
          <el-tab-pane label="服务区数据">
            <div v-if="serviceResults.length > 0" class="data-container">
              <el-table :data="serviceResults" stripe style="width: 100%">
                <el-table-column prop="service_name" label="服务区名称" />
                <el-table-column prop="service_level" label="等级" width="100" />
                <el-table-column prop="status" label="状态" width="100" />
                <el-table-column prop="facilities" label="设施描述" />
              </el-table>
            </div>
            <el-empty v-else description="没有服务区数据"></el-empty>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 地图容器 -->
    <div id="mapView" class="map-container"></div>

    <!-- 图层说明提示 -->
    <div class="layer-info-tip">
      <div class="tip-title">图层说明</div>
      <div class="tip-content">
        <div class="tip-item"><span class="color-box highway-good"></span> 高速公路 - 良好</div>
        <div class="tip-item"><span class="color-box highway-normal"></span> 高速公路 - 一般</div>
        <div class="tip-item"><span class="color-box highway-bad"></span> 高速公路 - 较差</div>
        <div class="tip-item"><span class="color-box highway-repair"></span> 高速公路 - 维修中</div>
        <div class="tip-item"><span class="color-box entrance"></span> 进出口</div>
        <div class="tip-item"><span class="color-box service"></span> 服务区</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { Search, PieChart } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol.js'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import Query from '@arcgis/core/rest/support/Query.js'
import Legend from '@arcgis/core/widgets/Legend.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'

// 地图相关变量
let view: MapView | null = null
let highwayLayer: FeatureLayer | null = null
let entranceLayer: FeatureLayer | null = null
let serviceLayer: FeatureLayer | null = null
let highlightLayer: GraphicsLayer | null = null

// 查询相关变量
const activeTab = ref('highway')
const highwayQuery = ref('')
const entranceQuery = ref('')
const serviceQuery = ref('')
let highwayResults = []
let entranceResults = []
let serviceResults = []
const hasSearched = ref(false)
const refreshKey = ref(0)
// 设施数据相关变量
const showFacilityData = ref(false)
const currentHighwayName = ref('')


// 处理标签页切换
const handleTabChange = () => {
  // 清除高亮显示
  if (highlightLayer) {
    highlightLayer.removeAll()
  }
}

// 切换设施数据显示状态
const toggleFacilityData = () => {
  showFacilityData.value = !showFacilityData.value
}

// 初始化地图
const initMap = async () => {
  try {
    // 创建进出口图层
    entranceLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayService/FeatureServer/0',
      outFields: ['*'],
      popupEnabled: true,
      popupTemplate: {
        title: '{entrance_name}',
        content: [
          {
            type: 'fields',
            fieldInfos: [
              { fieldName: 'entrance_id', label: '进出口编号' },
              { fieldName: 'entrance_type', label: '进出口类型' },
              { fieldName: 'highway_code', label: '所属高速公路' },
              { fieldName: 'status', label: '收费站状态' },
              { fieldName: 'location_desc', label: '位置描述' },
            ],
          },
        ],
      },
      // 设置进出口图层的样式
      renderer: {
        type: 'simple',
        symbol: new SimpleMarkerSymbol({
          style: 'square', // 使用方形标记
          color: '#3498DB', // 蓝色
          size: 10,
          outline: {
            color: '#2980B9',
            width: 1,
          },
        }),
        label: '高速公路进出口',
      },
    })

    // 创建服务区图层
    serviceLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayServiceLayer/FeatureServer/0',
      outFields: ['*'],
      popupEnabled: true,
      popupTemplate: {
        title: '{service_name}',
        content: [
          {
            type: 'fields',
            fieldInfos: [
              { fieldName: 'service_id', label: '服务区编号' },
              { fieldName: 'highway_code', label: '所属高速公路' },
              { fieldName: 'service_level', label: '服务区等级' },
              { fieldName: 'status', label: '服务区状态' },
              { fieldName: 'facilities', label: '设施描述' },
            ],
          },
        ],
      },
      // 设置服务区图层的样式
      renderer: {
        type: 'simple',
        symbol: new SimpleMarkerSymbol({
          style: 'diamond', // 使用菱形标记
          color: '#27AE60', // 绿色
          size: 12,
          outline: {
            color: '#1E8449',
            width: 1,
          },
        }),
        label: '高速公路服务区',
      },
    })

    // 创建高亮图层
    highlightLayer = new GraphicsLayer()

    // 创建地图
    const map = new Map({
      basemap: {
        baseLayers: [gaodeLayer],
      },
      layers: [entranceLayer, serviceLayer, highlightLayer],
    })

    // 创建地图视图
    view = new MapView({
      container: 'mapView',
      map: map,
      center: [116.404, 39.915], // 北京中心点坐标
      zoom: 10,
    })

    // 创建高速公路图层
    highwayLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayManagemnetSystem/FeatureServer/0',
      outFields: ['*'],
      popupEnabled: true,
      popupTemplate: {
        title: '{highway_name}',
        content: [
          {
            type: 'fields',
            fieldInfos: [
              { fieldName: 'highway_code', label: '高速公路编号' },
              { fieldName: 'highway_level', label: '高速公路等级' },
              { fieldName: 'lanes', label: '车道数' },
              { fieldName: 'status', label: '路况状态' },
              { fieldName: 'speed_limit', label: '限速(km/h)' },
            ],
          },
        ],
      },
      // 根据status字段设置唯一值渲染
      renderer: {
        type: 'unique-value',
        field: 'status',
        uniqueValueInfos: [
          {
            value: '良好',
            symbol: {
              type: 'simple-line',
              color: '#67C23A',
              width: '3px',
            },
          },
          {
            value: '一般',
            symbol: {
              type: 'simple-line',
              color: '#E6A23C',
              width: '3px',
            },
          },
          {
            value: '较差',
            symbol: {
              type: 'simple-line',
              color: '#F56C6C',
              width: '3px',
            },
          },
          {
            value: '维修中',
            symbol: {
              type: 'simple-line',
              color: '#EE1414',
              width: '3px',
            },
          },
        ],
      },
    })

    // 添加图层到地图
    map.add(highwayLayer)

    // 添加图例
    const legend = new Legend({
      view: view,
      layerInfos: [
        {
          layer: highwayLayer,
          title: '高速公路',
        },
        {
          layer: entranceLayer,
          title: '进出口',
        },
        {
          layer: serviceLayer,
          title: '服务区',
        },
      ],
    })

    // 将图例添加到右下角
    view.ui.add(legend, 'bottom-right')
  } catch (error) {
    console.error('初始化地图失败:', error)
    ElMessage.error('初始化地图失败')
  }
}

// 查询高速公路
const searchHighway = async () => {
  if (!highwayLayer) return
  if (!highwayQuery.value.trim()) {
    ElMessage.warning('请输入查询内容')
    return
  }

  try {
    const query = new Query()
    query.where = `highway_name LIKE '%${highwayQuery.value}%' OR highway_code LIKE '%${highwayQuery.value}%'`
    query.outFields = ['*']
    query.returnGeometry = true

    const results = await highwayLayer.queryFeatures(query)
    // Use spread operator to ensure reactivity
    highwayResults = results.features.map((feature) => feature.attributes)
    hasSearched.value = true

    // 清除高亮显示
    if (highlightLayer) {
      highlightLayer.removeAll()
    }

    if (results.features.length === 0) {
      ElMessage.info('未找到匹配的高速公路')
    } else {
      // 显示正在查询设施的提示
      ElMessage.info('正在查询相关设施...')

      // 对于所有查询到的高速公路，自动查询其设施
      for (const highway of results.features) {
        await queryFacilities(highway.attributes)
      }
      nextTick(() => {
        refreshKey.value++
      })

      // 清空进出口和服务区的搜索框
      entranceQuery.value = ''
      serviceQuery.value = ''

      // 如果查询到了设施，自动显示图表
      if (entranceResults.length > 0 || serviceResults.length > 0) {
        // 设置当前高速公路名称（用于图表标题）
        if (results.features.length === 1) {
          currentHighwayName.value = results.features[0].attributes.highway_name || ''
        } else {
          currentHighwayName.value = ''
        }

        // 显示设施数据
        showFacilityData.value = true
        // 切换到相应标签页
        if (entranceResults.length > 0) {
          nextTick(() => {
            activeTab.value = 'entrance'
          })
        } else if (serviceResults.length > 0) {
          nextTick(() => {
            activeTab.value = 'service'
          })
        }
      }

      // 如果只有一条结果，自动缩放到该高速公路
      if (results.features.length === 1) {
        zoomToHighway(results.features[0])
      }
    }
  } catch (error) {
    console.error('查询高速公路失败:', error)
    ElMessage.error('查询高速公路失败')
  } finally {
    nextTick(() => {
      refreshKey.value++
    })
  }
}

// 查询进出口
// 支持按进出口名称或高速公路编号(highway_code)查询
const searchEntrance = async () => {
  if (!entranceLayer) return
  if (!entranceQuery.value.trim()) {
    ElMessage.warning('请输入查询内容')
    return
  }

  try {
    const query = new Query()
    query.where = `entrance_name LIKE '%${entranceQuery.value}%' OR highway_code LIKE '%${entranceQuery.value}%'`
    query.outFields = ['*']
    query.returnGeometry = true

    const results = await entranceLayer.queryFeatures(query)
    // Use spread operator to ensure reactivity
    entranceResults = results.features.map((feature) => feature.attributes)
    hasSearched.value = true

    // 清除高亮显示
    if (highlightLayer) {
      highlightLayer.removeAll()
    }

    if (results.features.length === 0) {
      ElMessage.info('未找到匹配的进出口')
    } else if (results.features.length === 1) {
      // 如果只有一条结果，自动缩放到该进出口
      zoomToFeature(results.features[0])
    }
  } catch (error) {
    console.error('查询进出口失败:', error)
    ElMessage.error('查询进出口失败')
  }
}

// 查询服务区
// 支持按服务区名称或高速公路编号(highway_code)查询
const searchService = async () => {
  if (!serviceLayer) return
  if (!serviceQuery.value.trim()) {
    ElMessage.warning('请输入查询内容')
    return
  }

  try {
    const query = new Query()
    query.where = `service_name LIKE '%${serviceQuery.value}%' OR highway_code LIKE '%${serviceQuery.value}%'`
    query.outFields = ['*']
    query.returnGeometry = true

    const results = await serviceLayer.queryFeatures(query)
    // Use spread operator to ensure reactivity
    serviceResults = results.features.map((feature) => feature.attributes)
    hasSearched.value = true

    // 清除高亮显示
    if (highlightLayer) {
      highlightLayer.removeAll()
    }

    if (results.features.length === 0) {
      ElMessage.info('未找到匹配的服务区')
    } else if (results.features.length === 1) {
      // 如果只有一条结果，自动缩放到该服务区
      zoomToFeature(results.features[0])
    }
  } catch (error) {
    console.error('查询服务区失败:', error)
    ElMessage.error('查询服务区失败')
  }
}

// 缩放到高速公路
const zoomToHighway = (highway: any) => {
  if (!view || !highlightLayer) return

  // 清除之前的高亮显示
  highlightLayer.removeAll()

  // 创建高亮图形
  const highlightGraphic = new Graphic({
    geometry: highway.geometry,
    symbol: new SimpleLineSymbol({
      color: [255, 0, 0, 0.8],
      width: 5,
    }),
  })

  // 添加到高亮图层
  highlightLayer.add(highlightGraphic)

  // 缩放到高速公路
  view.goTo({
    target: highway.geometry,
    zoom: 12,
  })
}

// 缩放到点要素（进出口或服务区）
const zoomToFeature = async (feature: any,type:string) => {
  if (!view || !highlightLayer) return

  // 清除之前的高亮显示
  highlightLayer.removeAll()
  const query = new Query()
  query.where = `OBJECTID = ${feature.OBJECTID}`
  query.outFields = ['*']
  query.returnGeometry = true

  let results;
    if (type === 'entrance') {
      results = await entranceLayer.queryFeatures(query)
    } else if (type === 'service') {
      results = await serviceLayer.queryFeatures(query)
    }
  console.log(feature)
  console.log(results.features.length)
  // 创建高亮图形
  const highlightGraphic = new Graphic({
    geometry: results.features[0].geometry,
    symbol: new SimpleMarkerSymbol({
      color: [255, 0, 0, 0.8],
      size: 15,
      outline: {
        color: [255, 255, 255],
        width: 2,
      },
    }),
  })

  // 添加到高亮图层
  highlightLayer.add(highlightGraphic)

  // 缩放到要素
  view.goTo({
    target: results.features[0].geometry,
    zoom: 15,
  })
}

// 查询高速公路上的设施
// 使用highway_code字段在不同图层（进出口和服务区）中查询相关设施
const queryFacilities = async (highway: any) => {
  if (!entranceLayer || !serviceLayer || !highlightLayer || !view) return

  try {
    // 如果是从搜索结果中点击设施按钮调用，则清除之前的高亮显示
    // 如果是从搜索高速公路时自动调用，则保留之前的高亮显示
    const isCalledFromButton = activeTab.value === 'highway' // 判断是否是从按钮调用

    if (isCalledFromButton) {
      highlightLayer.removeAll()
      // 设置当前高速公路名称（用于图表标题）
      currentHighwayName.value = highway.highway_name || ''
    }

    // 高亮显示选中的高速公路
    const highwayGraphic = new Graphic({
      geometry: highway.geometry,
      symbol: new SimpleLineSymbol({
        color: [255, 0, 0, 0.8],
        width: 5,
      }),
    })
    highlightLayer.add(highwayGraphic)
    console.log(highway)
    // 查询该高速公路上的进出口
    const entranceQuery = new Query()
    entranceQuery.where = `highway_code = '${highway.highway_code}'`
    entranceQuery.outFields = ['*']
    entranceQuery.returnGeometry = true

    // 查询该高速公路上的服务区
    const serviceQuery = new Query()
    serviceQuery.where = `highway_code = '${highway.highway_code}'`
    serviceQuery.outFields = ['*']
    serviceQuery.returnGeometry = true

    // 并行执行查询
    const [entranceQueryResults, serviceQueryResults] = await Promise.all([
      entranceLayer.queryFeatures(entranceQuery),
      serviceLayer.queryFeatures(serviceQuery),
    ])
    console.log(entranceQueryResults.features)
    console.log(serviceQueryResults.features)
    for (let i = 0; i < entranceQueryResults.features.length; i++) {
      const feature = entranceQueryResults.features[i]
      const graphic = new Graphic({
        geometry: feature.geometry,
        symbol: new SimpleMarkerSymbol({
          style: 'square',
          color: [52, 152, 219, 0.8],
          size: 12,
          outline: {
            color: [255, 255, 255],
            width: 2,
          },
        }),
      })
      highlightLayer.add(graphic)
    }

    // 高亮显示服务区
    for (let i = 0; i < serviceQueryResults.features.length; i++) {
      const feature = serviceQueryResults.features[i]
      const graphic = new Graphic({
        geometry: feature.geometry,
        symbol: new SimpleMarkerSymbol({
          style: 'diamond',
          color: [39, 174, 96, 0.8],
          size: 14,
          outline: {
            color: [255, 255, 255],
            width: 2,
          },
        }),
      })
      highlightLayer.add(graphic)
    }

    entranceResults = entranceQueryResults.features.map((feature) => feature.attributes)
    console.log(entranceResults)
    serviceResults = serviceQueryResults.features.map((feature) => feature.attributes)
    nextTick(() => {
      refreshKey.value++
    })
    showFacilityData.value = true
  } catch (error) {
    console.error('查询设施失败:', error)
    ElMessage.error('查询设施失败')
  }
}

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (view) {
    view = null
  }
})
</script>

<style scoped>
.highway-query-container {
  height: 100%;
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
}

.query-panel {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 400px;
  z-index: 10;
}

.query-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background-color: rgba(255, 255, 255, 0.95);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.map-container {
  height: 100%;
  width: 100%;
  flex: 1;
}

.result-list {
  margin-top: 15px;
  max-height: 300px;
  overflow-y: auto;
}

/* 图层说明提示样式 */
.layer-info-tip {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 12px;
  z-index: 100;
  max-width: 200px;
  font-size: 12px;
}

.tip-title {
  font-weight: bold;
  margin-bottom: 8px;
  text-align: center;
  border-bottom: 1px solid #ddd;
  padding-bottom: 4px;
}

.tip-content {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.color-box {
  width: 16px;
  height: 16px;
  border-radius: 3px;
  display: inline-block;
}

.highway-good {
  background-color: #67c23a;
}

.highway-normal {
  background-color: #e6a23c;
}

.highway-bad {
  background-color: #f56c6c;
}

.highway-repair {
  background-color: #ee1414;
}

.entrance {
  background-color: #3498db;
}

.service {
  background-color: #27ae60;
}

/* 设施数据相关样式 */
.facility-data-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 600px;
  z-index: 10;
}

.data-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background-color: rgba(255, 255, 255, 0.95);
}

.data-container {
  max-height: 400px;
  overflow-y: auto;
  width: 100%;
}
</style>
